﻿package com.jd.dl.util;

import java.text.DecimalFormat;
import java.text.MessageFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

public class CommonUtils {

	private static Random rd = new Random();

	public static String generatePwd() {
		Long tmp = rd.nextLong();
		tmp = Math.abs(tmp);
		return tmp.toString().substring(0, 6);
	}

	public static String addZero(Integer src, int length) {
		String s = src.toString();
        for(; s.length() < length; s = "0" + s);
        return s;
    }

	public static String addZero(String s, int length) {
        for(; s.length() < length; s = "0" + s);
        return s;
    }

	public static String generateLoginNameNum() {
		Long tmp = rd.nextLong();
		tmp = Math.abs(tmp);
		return tmp.toString().substring(0, 6);
	}

	public static Date parse(String strDate, String pattern) {

		if (strDate == null || strDate.trim().length() == 0) {
			return null;
		}
		try {
			Date res = new SimpleDateFormat(pattern).parse(strDate);
			return res;
		} catch (ParseException e) {
			return null;
		}

	}

	public static String date2String(Date src) {
		// return date2String(src, "yyyy-MM-dd HH:mm:ss");
		return date2String(src, "yyyy-MM-dd");
	}

	public static String date2String(Date src, String pattern) {
		if (pattern == null) {
			pattern = "yyyy-MM-dd HH:mm:ss";
		}

		try {
			SimpleDateFormat format = new SimpleDateFormat(pattern);
			return format.format(src);
		} catch (Exception e) {
			return "";
		}

	}

	public static String double2String(Double src) {
		return double2String(src, "0.##");
	}

	public static String double2String(Double src, String pattern) {
		if (pattern == null || pattern.length() < 1) {
			pattern = "0.##";
		}
		DecimalFormat df=new DecimalFormat(pattern);
		String str = df.format(src);
		return str;
	}

	public static String formatString(String pattern, Object[] args) {
		if (pattern == null || pattern.length() < 1) {
			return "";
		}
		MessageFormat form = new MessageFormat(pattern);
		String message = form.format(args);
		return message;
	}

	/**
	 * Do convert the digit to Chinese
	 * 
	 * @param src
	 *            : int : min(0), max(99)
	 * @return String
	 */
	public static String int2Chinese(int src) {
		final String[] NUMBERS = { "零", "一", "二", "三", "四", "五", "六", "七", "八",
				"九" };
		final String[] UNITS = { "", "十" };

		String tmp = String.valueOf(src);
		StringBuffer res = new StringBuffer("");
		for (int i = tmp.length() - 1; i >= 0; i--) {
			int a = Integer.valueOf(tmp.substring(i, i + 1));
			if (a != 0) {
				res.insert(0, UNITS[tmp.length() - 1 - i]);
				if (tmp.length() - 1 - i != 1 || a != 1) {
					res.insert(0, NUMBERS[a]);
				}
			}
		}
		return res.toString();
	}
}
